package com.cby.operation.initialize.data

import android.text.TextUtils
import com.cby.operation.common.http.HttpHelper
import com.cby.operation.common.util.CbyLogUtils
import com.cby.operation.common.util.HandlerUtils
import com.cby.operation.common.util.ThreadPoolUtils
import com.cby.operation.sdk.*
import com.cby.operation.sdk.http.UrlHelper
import com.cby.operation.sdk.http.UrlHelper.buildSdkUrl
import com.cby.operation.sdk.util.VerifyUtils
import org.json.JSONException
import org.json.JSONObject
import java.lang.ref.WeakReference

/**
 * Description:SDK的初始化接口请求
 *
 * @author 陈宝阳
 * @create 2020/8/10 09:38
 */
internal object InitApiRepository {

    private const val TAG = "Init"
    private const val INIT_PATH = "game/init"
    //请求数据的回调接口对象的，弱引用
    private lateinit var reference: WeakReference<OnInitApiCallback>
    /**
     * SDK初始化url
     */
    private val INIT_BASE_URL = buildSdkUrl(INIT_PATH)

    fun initConfig(gameId: String?, callback: OnInitApiCallback?) {
        reference = WeakReference(callback)
        ThreadPoolUtils.execute(object : Runnable {
            override fun run() {
                //当前的时间戳
                val timeStamp = System.currentTimeMillis()
                //跟服务端约定的，国定规则签名
                val sign: String =
                    VerifyUtils.getVerifySign(gameId, "0", INIT_PATH, timeStamp.toString())

                val param: Map<String, Any> = HashMap<String, Any>().apply {
                    this[KEY_GAME_ID] = gameId!!
                    this[KEY_TIME_STAMP] = timeStamp
                    this[KEY_SIGN] = sign
                }

                HttpHelper.requestPost(
                    INIT_BASE_URL,
                    param,
                    UrlHelper.commonHeader,
                    object : HttpHelper.OnHttpRequestListener {

                        override fun onResponseSuccess(response: String?) {
                            try {
                                if (TextUtils.isEmpty(response)) {
                                    onResponseError(
                                        ERR_CODE_SERVER_EXCEPTION,
                                        ERR_MSG_SERVER_EXCEPTION
                                    )
                                    return
                                }
                                parseJsonData(response)
                            } catch (e: JSONException) {
                                onResponseError(ERR_CODE_SERVER_EXCEPTION, e.message)
                            }
                        }

                        override fun onResponseError(code: Int, errorMessage: String?) {
                            CbyLogUtils.e(TAG, errorMessage)
                            HandlerUtils.runOnMainThread(Runnable {
                                handleOnInitFailed(
                                    code,
                                    errorMessage
                                )
                            })
                        }
                    })
            }

        })
    }

    /**
     * 请求后的数据解析
     *
     * @param response
     * @throws JSONException
     */
    @Throws(JSONException::class)
    private fun parseJsonData(response: String?) {
        val data = JSONObject(response)
        val code = data.optInt(KEY_RESPONSE_CODE)
        val msg = data.optString(KEY_RESPONSE_MSG)
        val dataJson = data.optJSONObject(KEY_RESPONSE_DATA)
        HandlerUtils.runOnMainThread(Runnable {
            val config: InitConfig = InitConfig.parseJson(dataJson, code)
            when (code) {
                CODE_SUCCESS ->
                    //初始化成功，返回游戏配置信息
                    handleOnInitSucceed(config)
                CODE_GAME_MAINTENANCE ->
                    //返回初始化错误信息给游戏
                    handleOnInitMaintenance(config)
                else ->
                    //返回初始化错误信息给游戏
                    handleOnInitFailed(code, msg)
            }
        })
    }

    /**
     * 处理接口数据初始化状态成功的回调
     *
     * @param config InitConfig? [InitConfig]
     */
    private fun handleOnInitSucceed(config: InitConfig?) {
        reference.get()?.onInitSucceed(config)
    }

    /**
     *  处理接口初始化失败的回调
     *
     * @param code Int
     * @param msg String?
     */
    private fun handleOnInitFailed(code: Int, msg: String?) {
        reference.get()?.onInitFailed(code, msg)
    }

    /**
     * 处理接口初始化返回游戏维护的回调
     *
     * @param config InitConfig? [InitConfig]
     */
    private fun handleOnInitMaintenance(config: InitConfig?) {
        reference.get()?.onInitMaintenance(config)
    }

    /**
     * api初始化回调接口
     */
    interface OnInitApiCallback {
        /**
         * 初始化成功
         *
         * @param config
         */
        fun onInitSucceed(config: InitConfig?)

        /**
         * 初始化失败
         *
         * @param code
         * @param msg
         */
        fun onInitFailed(code: Int, msg: String?)

        /**
         * 维护
         *
         * @param config
         */
        fun onInitMaintenance(config: InitConfig?)
    }
}